<?php

namespace Repository;

use Doctrine\ORM\EntityRepository;

class UserRepository extends EntityRepository {
	
	public function login($data){
		return $this->_em->getRepository('Entity\ShUser')->findOneBy(array(
				'username' => $data['username'],
				'password' => $this->encrypt($data['password']),
				'status' => 1,
			));
	}
	
	private function encrypt($pass){
		return md5($pass);
	}
	public function backendPaginate($conf){
		$q = $this->_em->getRepository('Entity\ShUser')->findBy(
			$conf['condition'],$conf['order'],$conf['limit'],$conf['offset']
			);
		return $q;
	}
	public function addUser($data){
		$u = new \Entity\ShUser();

		$u->setUsername($data->post('ten-nguoi-dung'));
		$u->setPassword($this->encrypt($data->post('mat-khau')));
		$u->setRole($data->post('dac-quyen'));
		$u->setStatus($data->post('active'));
		$u->setDate(time());

		$this->_em->persist($u);
		$this->_em->flush();
		return true;
	}
	public function updateUser($data,$user){
		$user->setUsername($data->post('ten-nguoi-dung'));
		$user->setPassword($this->encrypt($data->post('mat-khau')));
		$user->setRole($data->post('dac-quyen'));
		$user->setStatus($data->post('active'));
		$user->setDate(time());

		$this->_em->persist($user);
		$this->_em->flush();
		return true;
	}
	public function deleteUser($user){
		$data = $this->_em->getRepository('Entity\ShUser')->findOneById($user);
		$this->_em->remove($data);
		$this->_em->flush();
		return true;
	}
	public function total_rows($pag){
		$q = $this->_em->createQueryBuilder()
		->select('COUNT(n.id)')
		->from('Entity\ShUser','n');
		return $q->getQuery()->getSingleScalarResult();
	}
	
	public function register($data){
		$user = new \Entity\ShUser();

		$user->setUsername($data->post('username'));
		$user->setPassword($this->encrypt($data->post('password')));
		$user->setRole(1);
		$user->setStatus(1);
		$user->setDate(time());
		
		$this->_em->persist($user);
		$this->_em->flush();
	
		$userinfo = new \Entity\ShUserinfo();
		$userinfo->setShUser($user);
		$userinfo->setFirstname($data->post('ho'));
		$userinfo->setLastname($data->post('ten'));
		$userinfo->setGender($data->post('gioi_tinh'));
		$userinfo->setEmail($data->post('emai'));
		$userinfo->setDate(time());
		
		$this->_em->persist($userinfo);
		$this->_em->flush();
		
		return $user;
	}
	public function getAllBy($user){
		$q = $this->_em->createQueryBuilder()
		->select('uf')
		->from('Entity\ShUserinfo','uf')
		->where('uf.shUser =?1')
		->setParameters(array(
			1 => $user
			));
		return $q->getQuery()->getResult();

	}
	
}